import { useState, useRef, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Card,
  Button, 
  Form,
  Input,
  Spin,
  Select,
  message
} from 'antd'
import E from 'wangeditor'
import moment from 'moment'
import { projectApi } from '../../api'
import { formItemLayout, tailFormItemLayout } from '../../config'

const { Option } = Select;
let editor: any = null

// 添加项目
export default function AddProject () {
  const [form] = Form.useForm();
  const [isLoading, setIsLoading] = useState(false)

  const navigate = useNavigate()
  const editorRef: any = useRef()

  useEffect(() => {
    // 注：class写法需要在componentDidMount 创建编辑器
    editor = new E(editorRef.current)
    // console.log('editor', editor)

    editor.onchange = (html: any) => {
      form.setFieldsValue({
        content: html
      })
    }

    // 需要展示的菜单
    editor.config.menus = [
      'head',
      'bold',
      'fontSize',
      'fontName',
      'italic',
      'underline',
      'strikeThrough',
      'indent',
      'lineHeight',
      'foreColor',
      'backColor',
      'link',
      'list',
      'todo',
      'justify',
      'quote',
      'table',
      'splitLine',
      'undo',
      'redo',
    ]

    // 创建 editor
    editor.create()

    return () => {
      // 组件销毁时销毁编辑器 注：class写法需要在componentWillUnmount中调用
      editor.destroy()
    }
  }, [form])

  // 表单提交
  const handleSubmit = (e: any) => {
    console.log('Received values of form: ', e);
    // 组装数据
    const data = Object.assign({}, e, {
      created: moment().valueOf(),
      url: e['urlPrefix'] + e['url'] + e['urlSuffix']
    })

    setIsLoading(true)
    console.log(data)

    projectApi.add(data)
      .then((res: any) => {
        console.log(res)
        if (res.code === 200) {
          message.success(res.data.msg)
          // 页面跳转
          navigate('/admin/project')
        } else {
          message.error(res.data.msg)
        }
      })
      .finally(() => {
        setIsLoading(false)
      })
  }

  const prefixSelector = (
    <Form.Item name="urlPrefix" noStyle>
      <Select style={{ width: 100 }} >
        <Option value="http://" >http://</Option>
        <Option value="https://">https://</Option>
      </Select>
    </Form.Item>
  );

  const suffixSelector = (
    <Form.Item name="urlSuffix" noStyle>
      <Select style={{ width: 100 }} >
        <Option value=".com">.com</Option>
        <Option value=".cn">.cn</Option>
        <Option value=".org">.org</Option>
      </Select>
    </Form.Item>
  );

  return (
    <Card 
      title="添加项目" 
      extra={<Button onClick={() => navigate(-1) }>取消</Button>} 
      style={{ width: '100%' }}
    >
      <Spin spinning={ isLoading }>
        <Form 
          form={ form }
          onFinish={ handleSubmit } 
          initialValues={{
            // residence: ['zhejiang', 'hangzhou', 'xihu'],
            urlPrefix: 'http://',
            urlSuffix: '.com',
            status: '0'
          }}
          { ...formItemLayout }
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              { required: true, message: '文章标题不能为空!' },
              { max: 10, message: '项目名称最长是10!' },
            ]}
          >
            <Input placeholder="项目名称" />
          </Form.Item>
          <Form.Item
            label="备案号"
            name='icp'
            rules={[{ required: true, message: '备案号不能为空' }]}
          >
            <Input placeholder="备案号" />
          </Form.Item>
          <Form.Item 
            label="网址" 
            name="url"
            tooltip="不能以访问协议开头，例如：http://"
            rules={[{ required: true, message: '网址不能为空' }]}
          >
            <Input 
              addonBefore={prefixSelector} 
              placeholder="www.domain" 
              addonAfter={suffixSelector}
            />
          </Form.Item>

          <Form.Item 
            label="内容" 
            rules={[{ required: true, message: '内容不能为空' }]}
          >
            {/* <Input.TextArea showCount maxLength={100} /> */}
            <div className="yy-editor" ref={ editorRef } />,
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '状态不能为空' }]}
          >
            <Select placeholder="选择状态">
              <Option value="0">已创建</Option>
              <Option value="1">设计中</Option>
              <Option value="2">已上线</Option>
              <Option value="3">已下线</Option>
            </Select>
          </Form.Item>

          <Form.Item { ...tailFormItemLayout } >
            <Button type="primary" htmlType="submit" >
              添加
            </Button>
          </Form.Item>
        </Form>
      </Spin>
    </Card>
  )
}